/**
 * Created by Administrator on 2016/3/12.
 */

(function ($) {

    $.fn.qrCode = function (options) {
        var _this = this;

        if (_this._timer) {
            _this._timer.timer('remove');
            _this._timer = null;
        }

        _this.settings = this.settings = $.extend({}, $.fn.qrCode.defaults, options);

        //if (($.brow.safari || $.brow.baidu) && window.location.hash != '#QRCODE') {
        if (($.brow.safari) && window.location.hash != '#QRCODE') {

            window.location.replace(_this.settings.crossUrl);

        //} else if ((!$.brow.safari && !$.brow.baidu) || window.location.hash == '#QRCODE') {
        } else if ((!$.brow.safari) || window.location.hash == '#QRCODE') {

            this.each(function () {

                var $element = $(this), $overlayContainer = $("iframe.iframe-container");

                if (!_this.settings.layer.instance) {
                    _this.settings.layer.instance = $element.qrLayer({
                        withClick: true,
                        withClickEvent: function () {
                            _this.settings.doLogin = false;
                            _this.settings.layer.instance.showOverLayer({tip: ''});
                            _this.settings.layer.options.withClickEvent();
                        }
                    });
                } else {
                    _this.settings.layer.instance.showOverLayer({tip: ''});
                }

                if ($overlayContainer.length == 0) {
                    createFrameContainer($element, _this.settings);
                } else {
                    if (_this._timer) {
                        _this._timer.timer('resume');
                    }
                    setTimeout(function(){
                        $overlayContainer.attr("src", urlAppendParams(_this.settings.genUrl, "r=" + new Date().getTime()));
                    }, 100);
                }


            });
        }

        function bindEventToTimerContainer(_this, $timerContainer, $element) {

            _this._timer = $timerContainer.timer({
                duration: 2,
                repeat: true,
                callback: function () {
                    asyncFunction(_this._timer, $element, _this.settings);
                }
            });
            _this.element = $element;

        }

        function createTimerContainer($element) {

            var $timerContainer = $('<input>').addClass('timer-container').css({
                display: 'none'
            }).attr("name", 'timer-container');

            $element.append($timerContainer);

            return $timerContainer;
        }

        function createFrameContainer($element, $settings) {

            var width = $element.outerWidth(),
                height = $element.outerHeight();

            var $overlayContainer = $('<iframe>').addClass('iframe-container').css({
                width: width,
                height: height,
                overflow: 'hidden',
                borderRadius: $element.css('border-radius')
            }).attr("scrolling", "no").attr("src", urlAppendParams(_this.settings.genUrl, "r=" + new Date().getTime()));

            $element.append($overlayContainer);

            $overlayContainer.load(function () {

                var $timerContainer = $("input.timer-container");
                if ($timerContainer.length == 0) {
                    $timerContainer = createTimerContainer($element);
                }
                if (_this._timer) {
                    _this._timer.timer('remove');
                }
                bindEventToTimerContainer(_this, $timerContainer, $element);
                $settings.layer.instance.removeOverLayer();

            });

            return $overlayContainer;
        }

        function asyncFunction($timer, $element, settings) {

            $.ajax({
                async: false,
                type: 'get',
                dataType: 'jsonp',
                jsonp: "callback",
                jsonpCallback: "callback",
                url: settings.statusUrl,
                success: function (result) {

                    if (result.returnCode == 0) {

                        $timer.timer('remove');
                        settings.doLogin = false;
                        statusAjax(result.data, settings);

                    } else if (result.returnCode == 404) {

                        $timer.timer('pause');
                        if (settings.layer.instance) {
                            settings.layer.instance.removeOverLayer();
                            settings.layer.instance.showOverLayer({
                                tip: settings.timeOutTip
                            });
                        }
                        settings.doLogin = false;

                    } else if (result.returnCode == 500) {

                        $timer.timer('pause');
                        if (settings.layer.instance) {
                            settings.layer.instance.removeOverLayer();
                            settings.layer.instance.showOverLayer({
                                tip: settings.timeOutTip
                            });
                        }
                        settings.doLogin = false;

                    } else if (result.returnCode == 200) {
                        if (!settings.doLogin) {
                            if (settings.layer.instance) {
                                settings.layer.instance.removeOverLayer();
                                settings.layer.instance.showOverLayer({
                                    tip: settings.loginTip
                                });
                            }
                            settings.doLogin = true;
                        }
                    }

                },
                error: function () {
                    if (settings.layer.instance) {
                        settings.layer.instance.removeOverLayer();
                        settings.layer.instance.showOverLayer({
                            tip: settings.timeOutTip
                        });
                    }
                }
            });
        }

        function statusAjax(url, settings) {
            $.ajax({
                async: false,
                type: 'get',
                dataType: 'jsonp',
                jsonp: "callback",
                jsonpCallback: "callback",
                url: url,
                success: function (data, status, xhr) {
                    settings.successAfter(data);
                },
                error: function (d) {
                    alert("error:" + d);
                }
            });
        }

        function urlAppendParams(url, param) {
            var r;
            if (url.match("[\?]")) {
                r = url + "&" + param;
            } else {
                r = url + "?" + param;
            }
            return r;
        }

        return {
            options: _this.settings,
            element: _this.element,
            _timer: _this._timer,
            reload: function () {
                var $overlayContainer = $("iframe.iframe-container");
                $overlayContainer.attr("src", urlAppendParams(_this.settings.genUrl, "r=" + new Date().getTime()));
                if (_this._timer) {
                    _this._timer.timer('resume');
                }
            },
            removeQrCode: function () {
                if (_this._timer) {
                    _this._timer.timer('remove');
                    _this._timer = null;
                }
                if (_this.settings.layer.instance) {
                    _this.settings.layer.instance.removeOverLayer();
                    _this.settings.layer.instance = null;
                }
            }
        }
    };

    $.fn.qrCode.defaults = {
        show: true,
        timeOutTip: '',
        loginTip: '',
        flushUrl: '',
        genUrl: '',
        statusUrl: '',
        crossUrl: '',
        layer: {
            options: {},
            instance: {}
        },
        doLogin: false,
        successAfter: function (result) {
            alert(result);
        }
    };

})(jQuery);